//
//  CCUserAccountToken.swift
//  swift_weibo
//
//  Created by ccl on 16/3/2.
//  Copyright © 2016年 LittleBoy. All rights reserved.
//

import UIKit

class CCUserAccountToken: NSObject , NSCoding{
    /// 记录用户令牌
    var access_token : String;
    /// 记录token的 有效时间
    var expires_in : NSTimeInterval;
    /// 记录用户获得 token的原始时间
    var expires_Date : NSDate;
    /// 用户uid
    var uid        : String;
    /// 用户昵称
    var name       : String?;
    /// 用户头像 url
    var avatar_large : String?;
    
    
    // 字典转模型
    init(dic: [String : AnyObject]) {
        access_token = dic["access_token"] as! String;
        expires_in   = dic["expires_in"] as! NSTimeInterval;
        expires_Date  = NSDate();
        uid = dic["uid"] as! String;
    }
    
    
    /// 通过  token和 uid 加载用户信息, 本来这个方法完全可以放在 CCUserLoginVC 控制器中, 但是为了练习 闭包当做参数传递的能力, 就写在这里. 
    ///  要求传入  finish: (account: CCUserAccountToken?, error: NSError?)->() 
    ///  闭包 需要传入 一个 可选CCUserAccountToken, 和一个可选 NSError 类型.
    ///  这个方法中是 调用外部传入的  封闭好的 闭包代码.
     func loadUserInfo(finish: (account: CCUserAccountToken?, error: NSError?)->() ){
    
        let url = "2/users/show.json";
        let parame = ["access_token" : access_token,"uid" : uid ];
        
       CCNetWorkingTooks.shareNetWorkingTook().GET(url, parameters: parame, progress: nil, success: { (_ , json) -> Void in
        
        let dic = json as! [String : AnyObject];
        self.name = dic["name"] as? String;
        self.avatar_large = dic["avatar_large"] as? String;
        
        self.saveAccount();
        // 获取用户信息成功, 调用 闭包方法
        finish(account: self, error: nil);
        
        
          }) { (_ , error ) -> Void in
        // 获取用户信息失败, 调用闭包方法.
            finish(account: nil, error: error);
        }
      
    }
    
    
    
    
    // 沙盒 路径
    static let searchPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last;
    
    static let filePath = searchPath!.stringByAppendingString("/userAccount.plist");
    
    
///  保存账号信息,
    func saveAccount() {
///   swift 中如果想用 静态变量, 需要用 类ming.静态变量
     
        NSKeyedArchiver.archiveRootObject(self, toFile: CCUserAccountToken.filePath);
        print(CCUserAccountToken.filePath);
    }
    ///  读取账号信息
  class func loadAccount() -> CCUserAccountToken?{
   
    // 读取账号信息
    if let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(CCUserAccountToken.filePath) as? CCUserAccountToken{
     // 判断是否过期
      let date = account.expires_Date.dateByAddingTimeInterval(account.expires_in);
        if date.compare(NSDate()) == NSComparisonResult.OrderedDescending{
          // 没哟过期,放回用户信息
            return account;
        }
    }
    // 过期返回 nil
    return nil;
    }

    
 // MARK: ---------------  nscoding 必须实现下面两个方法否则 会报错
   ///   编码 --> obj
    ///  解档方法，aDecoder 解码器，将保存在磁盘的二进制文件转换成 对象，和反序列化很像
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String;
        ///  因为decodeObjectForKey 返回的是 anyObject 所有要在后面用as! string 指明它是string类型,
        expires_in = aDecoder.decodeDoubleForKey("expires_in");
         /// decodeIntegerForKey, 已经指明是 int类型, 所以不用再用 as
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as! NSDate;
        uid = aDecoder.decodeObjectForKey("uid") as! String;
        
        name = aDecoder.decodeObjectForKey("name") as? String;
        
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String;
    }
    /// obj --> 编码
    func encodeWithCoder(aCoder: NSCoder) {
        
        aCoder.encodeObject(access_token, forKey: "access_token");
        aCoder.encodeDouble(expires_in, forKey: "expires_in");
        aCoder.encodeObject(expires_Date, forKey: "expires_Date");
        aCoder.encodeObject(uid, forKey: "uid");
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large");
        
        
    }
}
